package com.itheima.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 需求：定义全局过滤器，拦截请求，判断请求的参数是否满足下面条件：

 - 参数中是否有authorization，
 - authorization参数值是否为admin
 如果同时满足则放行，否则拦截

 */
@Component
@Order(-1) // 优先级，值越小优先级越高
public class AuthorizeFilter implements GlobalFilter {
    /**
     *
     * @param exchange 请求对象 （用于获取请求/响应参数）
     * @param chain 过滤器链 （用于放行或者拦截）
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        //1.获取请求参数
        MultiValueMap<String, String> queryParams = exchange.getRequest().getQueryParams();

        //2.判断参数中是否有authorization
        String authorization = queryParams.getFirst("authorization");

        //3.判断authorization参数值是否为admin
        if ("admin".equals(authorization)){
            //放行
            return chain.filter(exchange);
        }

        //4.否则拦截
        //4.1禁止访问设置状态码
        exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
        //4.2结束处理
        return exchange.getResponse().setComplete();
    }
}
